package cn.eastseven.netclient;

import java.net.InetSocketAddress;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaClient {

	private static final Logger log = LoggerFactory.getLogger(MinaClient.class);
	
	static final long CONNECT_TIMEOUT = 10000L;
	static final String HOSTNAME = "127.0.0.1";
	static final int PORT = 12345;
	
	public static void main(String[] args) {
		NioSocketConnector connector = new NioSocketConnector();
	    connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);

	    connector.getFilterChain().addLast("logger", new LoggingFilter());
	    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
	    connector.setHandler(new ClientSessionHandler());
	    IoSession session;

	    for (;;) {
	        try {
	            ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
	            future.awaitUninterruptibly();
	            session = future.getSession();
	            log.debug("connection is complete, associated IoSession. You can send msg to Server with this session.");
	            session.write("hello server, i am client \n");
	            session.write("q");
	            break;
	        } catch (RuntimeIoException e) {
	            e.printStackTrace();
	        }
	    }

	    // wait until the summation is done
	    session.getCloseFuture().awaitUninterruptibly();
	    connector.dispose();
	}

}

class ClientSessionHandler extends IoHandlerAdapter {
	
	static final Logger log = LoggerFactory.getLogger(ClientSessionHandler.class);
	
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		super.messageReceived(session, message);
		log.debug("messageReceived: sessionId={}, msg={}", session.getId(), message);
		if(message.toString().contains("OK")) {
			log.debug("通讯结束");
			session.close(true);
		}
	}
	
	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		super.messageSent(session, message);
		log.debug("messageSent: sessionId={}, msg={}", session.getId(), message);
	}
}
